import { ApiMsgEnum, IRoom, Singleton } from "../Common";
import { PlayerManager } from "./PlayerManager";
import { Room } from "./Room";

export class RoomManager extends Singleton {
    static get Ins() {
        return super.GetInstance<RoomManager>()
    }

    nextRoomId = 1
    rooms: Set<Room> = new Set()
    idMapRoom: Map<number, Room> = new Map()
    createRoom() {
        const room = new Room(this.nextRoomId++)
        this.rooms.add(room)
        this.idMapRoom.set(room.rid, room)
        return room
    }

    closeRoom(room: Room) {
        this.rooms.delete(room)
        this.idMapRoom.delete(room.rid)
        console.log(`房间${room.rid}关闭`)
        for (const timer of room.times) {
            clearInterval(timer)
        }
    }

    getRoomsView(rooms: Set<Room> = this.rooms): IRoom[] {
        return [...rooms].map(v => this.getRoomView(v))
    }

    getRoomView({ rid, players, isGaming }: Room): IRoom {
        return {
            rid,
            isGaming,
            players: PlayerManager.Ins.getPlayersView(players)
        }
    }

    getRoomById(id: number) {
        return this.idMapRoom.get(id)
    }

    /** 向大厅所有玩家广播消息，同步房间信息 */
    syncHall() {
        for (const { rid, connection } of PlayerManager.Ins.players) {
            if (rid === 0) {
                connection.sendMsg(ApiMsgEnum.MsgHallSync, {
                    rooms: this.getRoomsView()
                })
            }
        }
    }

}